package com.dcjt.firehotcarpad.retrofit1

import android.text.TextUtils
import com.aries.library.fast.manager.LoggerManager
import com.juntu.loginlib.contact.LoginConstant
import com.juntu.loginlib.contact.LoginUrl
import com.juntu.loginlib.util.LoginUtil
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.json.JSONObject
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

/**
 * Created by cj on 2021/3/1.
 * Email:codesexy@163.com
 * Function:
 * desc:处理token失效引起的问题
 */
class TokenInvalidInterceptor(
    private var client: OkHttpClient =
        OkHttpClient
            .Builder()
            .callTimeout(20, TimeUnit.SECONDS)
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .build()
) : Interceptor {


    override fun intercept(chain: Interceptor.Chain): Response {

        val request = chain.request()
        val response = chain.proceed(request)
        val responseBody: ResponseBody? = response.body

        val source = responseBody?.source()
        source?.request(Long.MAX_VALUE)
        val buffer = source?.buffer()
        var charset = Charset.forName("UTF8")

        val contentType = responseBody?.contentType()

        if (contentType != null) {
            charset = contentType.charset(Charset.forName("UTF8"))
        }

        val result = buffer?.clone()?.readString(charset!!)

        if (TextUtils.isEmpty(result)) {
            return response
        }

        try {
            val json = JSONObject(result)
            val code = json.optInt("code")
            if (code == 203) {
                // token 失效
                return doLogin(chain)
            } else {
                return response
            }

        } catch (e: Exception) {
            return response
        }
    }


    private fun doLogin(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val newRequest = request.newBuilder().build()

        val loginUrl = LoginUrl.getLoginUrl()
        val httpUrl = loginUrl.toHttpUrlOrNull()!!.newBuilder()

        var psw = LoginUtil.getStr(LoginConstant.USER_PSW)
        var userName = LoginUtil.getStr(LoginConstant.USER_NAME)
        var loginType = LoginUtil.getStr(LoginConstant.DEVICE_TYPE)
        var placeId = LoginUtil.getStr(LoginConstant.PLACE_ID)

        val url = httpUrl.addQueryParameter("password", psw)
            .addQueryParameter("username", userName)
            .addQueryParameter("dlzdlx", loginType)
            .addQueryParameter("dlcslx", placeId)
            .addQueryParameter("sbbh", LoginUtil.getDeviceId())
            .build()
        var loginRequest = Request.Builder().url(url).build()

        val loginResponse = client.newCall(loginRequest).execute()
        if (loginResponse.isSuccessful) {
            val loginBody = loginResponse.body?.string()
            com.dcjt.firehotcarpad.utils.LoginUtil.parseLoginResult(loginBody)
        } else {
            LoggerManager.e("TokenInvalidInterceptor", "刷新Token失败")
        }

        return chain.proceed(newRequest)
    }

}